package com.qbccn.onlinetest.service.impl;

import com.qbccn.onlinetest.domain.OtUser;
import com.qbccn.onlinetest.domain.RbRole;
import com.qbccn.onlinetest.service.UserService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author linke
 * @date 2020/5/23 18:31
 * @description
 */
@Component
public class CustomUserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserService userService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    if (StringUtils.isEmpty(username)) {
      throw new UsernameNotFoundException(null);
    }
    OtUser user = userService.getUserInfo(username);
    if (user == null) {
      throw new UsernameNotFoundException("账号不存在！");
    }
    if (user.getStatus() == 0) {
      throw new RuntimeException("账号无效");
    }
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    List<RbRole> roles = userService.getUserRoles(username);
    roles.forEach(r -> {
      //security的验证规则需要ROLE_
      grantedAuthorities.add(new SimpleGrantedAuthority(r.getRoleName()));
    });
    return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), grantedAuthorities);
  }
}
